﻿package com.projects.xenia;

import java.util.Calendar;

import com.projects.xenia.R.id;
import com.projects.xenia.global_modules.MainGlobalModule;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

public class Activity_CustomersInfo extends Activity {

	private Bundle DocExtras;
	private String CustomerId;
	
	private String CustomerDescrFull;
		
	private TextView custinf_descr;
	private TextView custinf_telephone;
	private TextView custinf_hours;
	private TextView custinf_days;
	
	private TextView custinf_gps;
	private TextView custinf_contact;
	private TextView custinf_turnover;
	private TextView custinf_categories;
	private TextView custinf_discounts;
	private TextView custinf_agreements;
	private TextView custinf_licenses;
	private ImageView inf_gpsbutton;
	private TextView custinf_stockintrade;
	private ImageView BackWardButton; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

		DocExtras = getIntent().getExtras();
		CustomerId = DocExtras.getString("CustomerId");
		
		setContentView(R.layout.customers_info_form);
		
		
		BackWardButton = (ImageView)findViewById(R.id._backward);
		BackWardButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		// основная часть
		Cursor CustomerCursor = MainGlobalModule.DBE.rawQuery("select * from xref_customers where id = ?",new String [] {CustomerId});
		CustomerCursor.moveToFirst();
		
		custinf_descr = (TextView)findViewById(R.id.custinf_descr);		
		String CustomerDescr = CustomerCursor.getString(CustomerCursor.getColumnIndex("descr")); 
		String OutletDescr = CustomerCursor.getString(CustomerCursor.getColumnIndex("outletdescr"));
		String OutletAdress = CustomerCursor.getString(CustomerCursor.getColumnIndex("outletadress"));
		if (OutletDescr.equals(OutletAdress)) {OutletAdress = "";}
		CustomerDescrFull = String.format("%s, %s, %s", CustomerDescr,OutletDescr,OutletAdress);
		custinf_descr.setText(CustomerDescrFull);
		
		custinf_telephone = (TextView)findViewById(R.id.custinf_telephone);
		String OutletTelephone = CustomerCursor.getString(CustomerCursor.getColumnIndex("outlettelephone"));
		custinf_telephone.setText(OutletTelephone);
		
		custinf_hours = (TextView)findViewById(R.id.custinf_hours);
		String OpenTime = CustomerCursor.getString(CustomerCursor.getColumnIndex("opentime"));
		String CloseTime =  CustomerCursor.getString(CustomerCursor.getColumnIndex("closetime"));
		String BreackTimeFrom = CustomerCursor.getString(CustomerCursor.getColumnIndex("breacktimefrom"));
		String BreackTimeTo = CustomerCursor.getString(CustomerCursor.getColumnIndex("breacktimeto"));
		custinf_hours.setText(String.format("С %s по %s ; Перерыв: с %s по %s ", OpenTime,CloseTime,BreackTimeFrom,BreackTimeTo));
		
		// дни посещений
		custinf_days = (TextView)findViewById(R.id.custinf_days);
		Cursor RouteCursor = MainGlobalModule.DBE.rawQuery("select distinct dayofroute from xref_Routes where customers_id = ? and position > 0 order by dayofroute",new String [] {CustomerId});		
		String Days = "";
		if (RouteCursor.getCount()>0) {
			RouteCursor.moveToFirst();		
			
			String [] week = new String [] {"?","Пн;", "Вт;","Ср;","Чт;","Пт;","Сб;","Вс;"};		
		
			do {			
				Days = Days.concat(week[RouteCursor.getInt(RouteCursor.getColumnIndex("dayofroute"))]);
			}
			while (RouteCursor.moveToNext());
		}
		custinf_days.setText(Days);
	
		
		
		custinf_turnover = (TextView)findViewById(id.custinf_turnover);		
		String turnover = "";		
		Cursor TurnOverCursor = MainGlobalModule.DBE.rawQuery("select sum (total_ordersum),count (*) from xdoc_orders_h where total_ordersum > 0 and customers_id = ? and date (date_create) >= date ('now','-30 day')",new String [] {CustomerId});
		if (TurnOverCursor.getCount()>0) {
			TurnOverCursor.moveToFirst();
			turnover = String.format("%.0f заказ(ов) на сумму %.2f ", TurnOverCursor.getDouble(1),TurnOverCursor.getDouble(0));
		}
		custinf_turnover.setText(turnover);
		
		// категории
		custinf_categories = (TextView)findViewById(id.custinf_categories);
		Cursor CategoryCursor = MainGlobalModule.DBE.rawQuery("select cat.descr as descr from xref_CustomersCategory cst inner join xref_Category cat on cst.category_id = cat.id and cst.customers_id = ?",new String [] {CustomerId});		
		String Categories = "";
		if (CategoryCursor.getCount()>0) {
			CategoryCursor.moveToFirst();
			do {			
				Categories = Categories.concat(String.format("%s;%n", CategoryCursor.getString(0)));
			}
			while (CategoryCursor.moveToNext());
		}
		custinf_categories.setText(Categories);

		// цены и скидки
		custinf_discounts = (TextView)findViewById(id.custinf_discounts);
		Cursor DiscountsCursor = MainGlobalModule.DBE.rawQuery("select distinct ifnull (g.descr_long,'') as goodsdescr, p.descr as pricedescr, -d.discount as discount from xref_CustomersDiscounts d left outer join xref_PriceCategory p on d.pricecategory_id = p.id left outer join xref_Goods g on d.goods_id = g.id where d.customers_id = ? order by goodsdescr,is_default desc",new String [] {CustomerId});		
		String Discounts = "";
		if (DiscountsCursor.getCount()>0) {
			DiscountsCursor.moveToFirst();
			do {
				String GoodsDescr = DiscountsCursor.getString(DiscountsCursor.getColumnIndex("goodsdescr")); 
				String PriceDescr = DiscountsCursor.getString(DiscountsCursor.getColumnIndex("pricedescr"));
				String Discount = String.valueOf(DiscountsCursor.getDouble(DiscountsCursor.getColumnIndex("discount")));				
				Discounts = Discounts.concat(String.format("%s /%s(%s)/;%n", GoodsDescr,PriceDescr,Discount));
			}
			while (DiscountsCursor.moveToNext());
		}
		custinf_discounts.setText(Discounts);
		
		// договора 		
		custinf_agreements = (TextView)findViewById(id.custinf_agreements);
		Cursor AgreementsCursor = MainGlobalModule.DBE.rawQuery("select f.descr as firm, d.number as number, date (d.datebegin) as datebegin, date (d.dateend) as dateend from xref_customersagreements d inner join xref_firms f on d.firms_id = f.id where d.customers_id = ?",new String [] {CustomerId});
		String Agreements = "";
		if (AgreementsCursor.getCount()>0) {
			AgreementsCursor.moveToFirst();
			do {
				String FirmString = AgreementsCursor.getString(AgreementsCursor.getColumnIndex("firm"));
				String NumberString = AgreementsCursor.getString(AgreementsCursor.getColumnIndex("number"));
				String DateBeginString = AgreementsCursor.getString(AgreementsCursor.getColumnIndex("datebegin"));
				String DateEndString = AgreementsCursor.getString(AgreementsCursor.getColumnIndex("dateend"));						
				Agreements = Agreements.concat(String.format("%s%n№%s от %s по %s%n", FirmString,NumberString,DateBeginString,DateEndString));
			}
			while (AgreementsCursor.moveToNext());
		}
		custinf_agreements.setText(Agreements);
		
		
		custinf_licenses = (TextView)findViewById(id.custinf_licenses);
		Cursor LicensesCursor = MainGlobalModule.DBE.rawQuery("select descr as descr, date (datebegin) as datebegin, date (dateend) as dateend from xref_customerslicenses where customers_id = ?",new String [] {CustomerId});
		String Licenses = "";
		if (LicensesCursor.getCount()>0) {
			LicensesCursor.moveToFirst();
			do {
				String DescrString = LicensesCursor.getString(LicensesCursor.getColumnIndex("descr"));				
				String DateBeginString = LicensesCursor.getString(LicensesCursor.getColumnIndex("datebegin"));
				String DateEndString = LicensesCursor.getString(LicensesCursor.getColumnIndex("dateend"));						
				Licenses = Licenses.concat(String.format("от %s по %s %s %n", DateBeginString,DateEndString,DescrString));
				}
			while (LicensesCursor.moveToNext());
			}
		custinf_licenses.setText(Licenses);
		
		inf_gpsbutton = (ImageView)findViewById(id.inf_gpsbutton);
		inf_gpsbutton.setOnClickListener(inf_gpsbutton_click);
		inf_gpsbutton.setVisibility(View.INVISIBLE);
		custinf_gps = (TextView)findViewById(id.custinf_gps);	
		String GpsString = "";
		Cursor GpsCursor = MainGlobalModule.DBE.rawQuery("select lat,lon from xref_customersgps where customers_id = ?",new String [] {CustomerId});
		if (GpsCursor.getCount()>0) {
			GpsCursor.moveToFirst();
			GpsString = String.format("шир.:%s,долг.:%s", GpsCursor.getString(0),GpsCursor.getString(0));
			inf_gpsbutton.setVisibility(View.VISIBLE);			
		}
		custinf_gps.setText(GpsString);
		
		custinf_contact = (TextView)findViewById(id.custinf_contact);		
		
		
		custinf_stockintrade = (TextView)findViewById(id.custinf_stockintrade);
		Cursor StockInTradeCursor = MainGlobalModule.DBE.rawQuery("select st.descr as descr, cs.rest_count as rest_count from xref_stockintrade st inner join xref_customersstockintrade cs on st.id = cs.stockintrade_id where cs.customers_id = ? order by st.descr",new String [] {CustomerId});
		String StockInTrade = "";
		if (StockInTradeCursor.getCount()>0) {
			StockInTradeCursor.moveToFirst();
			do {
				String StockDescr = StockInTradeCursor.getString(StockInTradeCursor.getColumnIndex("descr"));				
				Double StockRest = StockInTradeCursor.getDouble(StockInTradeCursor.getColumnIndex("rest_count"));										
				StockInTrade = StockInTrade.concat(String.format("(%.0f) %s%n", StockRest,StockDescr));
				}
			while (StockInTradeCursor.moveToNext());
			}
		custinf_stockintrade.setText(StockInTrade);
		
		StockInTradeCursor.close ();
		LicensesCursor.close ();
		GpsCursor.close();		
		CategoryCursor.close ();
		RouteCursor.close();
		CustomerCursor.close();
		TurnOverCursor.close();
		
	}
	
	private OnClickListener inf_gpsbutton_click = new OnClickListener() {
		@Override
		public void onClick(View v) {
			
			Cursor GpsCursor = MainGlobalModule.DBE.rawQuery("select lat,lon from xref_customersgps where customers_id = ?",new String [] {CustomerId});
			if (GpsCursor.getCount()>0) {
				GpsCursor.moveToFirst();
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("geo:%s,%s?z=50&q=<%s>,<%s>(%s)",GpsCursor.getString(0),GpsCursor.getString(1),GpsCursor.getString(0),GpsCursor.getString(1),CustomerDescrFull)));
				startActivity(intent);			
			}
		}
	};
	
}
